package com.herr.springboot.self.xxx.common.util;

import com.herr.springboot.self.xxx.common.enums.ApiResultEnum;
import com.herr.springboot.self.xxx.common.entity.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;

import java.util.List;

/**
 * 接口响应处理工具类
 * @author herr05
 */
@Slf4j
public class ResponseUtils {
    public static ApiResult handleNotValidException(Exception e) {
        BindingResult result;
        if (e instanceof BindException) {
            BindException exception = (BindException) e;
            result = exception.getBindingResult();
        } else {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            result = exception.getBindingResult();
        }

        StringBuilder builder = new StringBuilder("参数校验失败。");
        List<ObjectError> allErrors = result.getAllErrors();
        allErrors.stream().findFirst().ifPresent(error -> {
            builder.append(((FieldError) error).getField()).append("字段规则为:").append(error.getDefaultMessage());
        });
        ApiResult apiResult=ApiResult.builder().code(ApiResultEnum.PARAM_ERR.getCode()).msg(builder.toString()).build();
        LogUtils.doAfterException(apiResult);
        return apiResult;
    }
}
